var t = getApp();
var app = getApp();
// 在页面中定义插屏广告
let interstitialAd = null

Page({
    data: {
        login: false,
        goodList: [],
        unit_id: "",
        setting: {
            unit_id: "",
            kf_wxid: ""
        },
        loginCompStatus: !1
    },
    onLoad: function(i) {

        // 在页面onLoad回调事件中创建插屏广告实例
        if (wx.createInterstitialAd) {
            interstitialAd = wx.createInterstitialAd({
            adUnitId: 'adunit-55dbf36ab0db90b0'
            })
            interstitialAd.onLoad(() => {})
            interstitialAd.onError((err) => {})
            interstitialAd.onClose(() => {})
        }
        
        this.onQuery();
        // t.unit_id && this.setData({
        //     unit_id: t.unit_id
        // }), this.initGoods();
    },
    onQuery: function(){
        const db = wx.cloud.database()
        db.collection('goods')
        .get().then(res => {
          console.log('[数据库] [查询记录] 成功: ', res)
          wx.hideLoading()
          let arr = res.data;
          let goodList = [];
          arr.forEach((element,index) => {
              element.index = index;
              goodList.push(element);
          });
          this.setData({
            goodList
          });
        })
    },
    copyKfWx: function() {
        var t = this.data.setting;
        "" != t.kf_wxid && wx.setClipboardData({
            data: t.kf_wxid,
            success: function(t) {
                wx.showModal({
                    title: "复制成功",
                    content: "客服微信号复制成功，请添加微信，审核您的历史兑换",
                    confirmText: "我知道了",
                    confirmColor: "#fd5757",
                    success: function(t) {}
                });
            }
        });
    },
    initGoods: function() {
       
    },
    returnPrev: function() {
        wx.navigateBack();
    },
    goInfo: function() {
        this.data.login ? wx.navigateTo({
            url: t.pages.info
        }) : this.showLoginModal();
    },
    goRecord: function() {
        this.data.login ? wx.navigateTo({
            url: t.pages.record
        }) : this.showLoginModal();
    },
    showLoginModal: function() {
        this.setData({
            loginCompStatus: true
        });
    },
    pgLoginCancel: function() {
        this.setData({
            loginCompStatus: !1
        });
    },
    pgLoginConfirm: function(i) {
        var o = i.detail.result, n = this;
        if (o.userInfo) {
            var a = o.userInfo;
            a.vid = n.data.vid, t.register(a, n.loginCallback), n.setData({
                loginCompStatus: !1
            });
        } else console.log("用户未允许授权");
    },
    addOrders: function(good){
        const db = wx.cloud.database();
        const _ = db.command;
        db.collection('orders').add({
          // data 字段表示需新增的 JSON 数据
          data: {
            userInfo: app.globalData.userInfo,
            name: good.name,
            price: good.price,
            status: '处理中',
            time: this.data.time
          }
        })
        .then(res => {
          console.log(res)
          console.log('[数据库] [查询记录] 成功: ', res);
          wx.showToast({
            title: '兑换成功',
            icon: 'success',
            duration: 2000
          })
          
        })
        .catch((err)=>{
          console.log(err)
    
        })


    },
    doExchange: function(e) {
        let index = e.currentTarget.dataset.index;
        let good = this.data.goodList[index];
        let that = this;
        if (this.data.login) {
            if(this.data.balance < good.price){
                wx.showToast({
                    title: '余额不足',
                    icon: 'none',
                    duration: 2000
                })
                return;
                  
            }
            wx.showModal({
                title: "兑换确认",
                content: "您确定要使用 " + good.price + " 元来兑换这个商品吗",
                cancelText: "考虑一下",
                confirmText: "立即兑换",
                confirmColor: "#5735B7",
                success: function(i) {
                    that.addOrders(good);
                }
            });
            return;
            var o = t.user;
            if ("" != o.realname && "" != o.mobile && "" != o.wxid) {
                var n = this, a = i.currentTarget.dataset.index, s = this.data.goodList[a], e = i.detail.formId;
                wx.showModal({
                    title: "兑换确认",
                    content: "您确定要使用 " + s.price + " 元来兑换这个商品吗",
                    cancelText: "考虑一下",
                    confirmText: "立即兑换",
                    confirmColor: "#5735B7",
                    success: function(i) {
                        i.confirm && t.util.request({
                            url: "entry/wxapp/exchange",
                            data: {
                                form_id: e,
                                goods_id: s.id
                            },
                            success: function(i) {
                                if (0 == i.data.code) return n.initGoods(), t.refreshUser = !0, void t.happy("兑换成功");
                                t.sad(i.data.message);
                            },
                            fail: function(t) {
                                console.log("请求积分商品:fail");
                            }
                        });
                    }
                });
            } else t.sad("请先完善信息");
        } else this.showLoginModal();
    },
    onReady: function() {
        t.initConfig(this.initConfigBack);
    },
    initConfigBack: function() {
        var t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : null, i = this;
        if (null != t) {
            var o = t.setting;
            o.status && i.setData({
                setting: o.data
            });
        }
    },
    onShow: function() {

        // 在适合的场景显示插屏广告
        if (interstitialAd) {
            interstitialAd.show().catch((err) => {
            console.error(err)
            })
        }
        
        this.onGetTime();
        this.setData({
            balance: app.globalData.balance,
            login: app.globalData.login
        })
    },
    onGetTime: function() {
        let that = this;
        // 调用云函数
        wx.cloud.callFunction({
          name: 'getTime',
          data: {}
        })
        .then(res=>{
          console.log('[云函数] [getTime]: ', res)
          that.setData({
            time: res.result.time,
            today: res.result.today
          })
        })
        .catch(err=>{
          console.error('[云函数] [getTime] 调用失败', err)
          wx.navigateTo({
            url: '../deployFunctions/deployFunctions',
          })
        })
      }
});